package com.phpxiu.app.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.phpxiu.app.adapter.HomeFollowListAdapter;
import com.phpxiu.app.api.callback.EnterRoomChecker;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.list.HomeFollow;
import com.phpxiu.app.model.response.HomeFollowListMode;
import com.phpxiu.app.model.response.HomeHistoryModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.RoomVideoRoom;
import com.phpxiu.app.view.custom.ListEmptyView;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by WuJinZhou on 2016/5/5.
 */
public class HomeFollowFragment extends BaseFragment implements PullToRefreshView.OnRefreshListener2<ListView> {
    public final static String TAG="HomeFollowFragment";
    private final static int HANDLE_REFRESH_COMPLETE=0x1;
    private int mScreenWidth;
    private PullToRefreshListView ptRefreshView;
    private ListView mListView;
    private ListEmptyView emptyView;
    private HomeFollowListAdapter mAdapter;
    private List<HomeFollow>lives=new ArrayList<HomeFollow>();
    private List<HomeFollow>history=new ArrayList<HomeFollow>();
    private List<HomeFollow>follows=new ArrayList<HomeFollow>();
    private HomeFollow emptyItem,labelItem;
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=15;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;
    public static BaseFragment builder(String arg){
        HomeFollowFragment fragment=new HomeFollowFragment();
        Bundle b = new Bundle();
        b.putString(ARG,arg);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        emptyItem=new HomeFollow();
        emptyItem.setListViewType(HomeFollow.TYPE_EMPTY_LIVING);
        labelItem=new HomeFollow();
        labelItem.setListViewType(HomeFollow.TYPE_HISTORY_ITEM_LABEL);
        mScreenWidth=(int) KKYApp.getInstance().screenWidth;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.home_follow_fragment,null);
        emptyView=new ListEmptyView(getActivity());
        emptyView.setMsg(getString(R.string.list_empty_title));
        init();
        return rootView;
    }

    /**
     * 初始化视图
     */
    private void init(){
        ptRefreshView=(PullToRefreshListView)rootView.findViewById(R.id.home_follow_pull_refresh_list);
        ptRefreshView.setOnRefreshListener(this);
        mListView=ptRefreshView.getRefreshableView();
        mListView.setEmptyView(emptyView);
        mListView.setDivider(null);
        mAdapter=new HomeFollowListAdapter(act,follows,mScreenWidth);
        mAdapter.setOnEnterRoomCallBack(this);
        mListView.setAdapter(mAdapter);
        request(mOpera);
    }

    /**
     * 请求数据初始化
     */
    private void request(int opera){
        mOpera=opera;
        if(param==null){
            param= OKHttpParam.builder();
            param.put("pageSize",pageSize);
        }
        param.put("pageIndex",1);
        if(mOpera== HttpConfig.REQUEST_OPERA_LOAD){
            param.put("pageIndex",pageIndex==1?2:pageIndex);
        }
        OKHttp.post(HttpConfig.API_HOME_ATTENTION_LIST, param.jsonParam(), TAG, new OKHttpUIHandler(HomeFollowListMode.class) {
            @Override
            public void onSuccess(Object model) {
                emptyView.loaded();
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                try {
                    HomeFollowListMode m = (HomeFollowListMode) model;
                    KKYUtil.log(TAG, "首页关注列表数据：" + m.getResponseStr());
                    follows.clear();
                    if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                        currentAllRecords = m.getData().getTotalItem();
                        history.clear();
                        lives.clear();
                        pageIndex = 1;
                        loadLives(m.getData().getRecordList(), true);
                    } else {
                        if (currentAllRecords > 0 && follows.size() > 0 && follows.size() < currentAllRecords) {
                            pageIndex++;
                        }
                        loadLives(m.getData().getRecordList(), false);
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onErr(String errMsg) {
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                listEmpty(follows.size() == 0);
            }
        });
    }

    /**
     * 加载正在直播的数据
     */
    private void loadLives(List<HomeFollow> data,boolean refresh){
        if(refresh){
            lives.clear();
            history.clear();
        }

        if(history.contains(labelItem)){
            history.remove(labelItem);
        }

        if(lives.contains(emptyItem)){
            lives.remove(emptyItem);
        }

        for (HomeFollow follow:data){
            follow.setListViewType(HomeFollow.TYPE_LIVING_ITEM);
            lives.add(follow);
        }
        if(lives.size()==0){
            lives.add(0,emptyItem);
        }
        if(lives.size()<15&&history.size()==0){//正在直播数据不足一页
            getHistory();
        }else{
            follows.addAll(lives);
            if(history.size()>0){
                history.add(0,labelItem);
                follows.addAll(history);
            }
            mAdapter.notifyDataSetChanged();
            listEmpty(follows.size() == 0);
        }
    }

    /**
     * 请求历回放数据
     */
    private void getHistory(){
        OKHttpParam p= OKHttpParam.builder(false);
        OKHttp.post(HttpConfig.API_HOME_FOLLOW_HISTORY_LIST, p.jsonParam(), TAG, new OKHttpUIHandler(HomeHistoryModel.class) {
            @Override
            public void onSuccess(Object model) {
                HomeHistoryModel m = (HomeHistoryModel) model;
                KKYUtil.log("首页关注回放记录数据：" + m.getResponseStr());
                loadHistory(m.getData());
            }

            @Override
            public void onErr(String errMsg) {
                KKYUtil.log("首页关注回放记录数据加载出错：" + errMsg);
            }
        });
    }

    /**
     * 加载录制数据
     */
    private void loadHistory(List<HomeFollow> data){
        for (HomeFollow follow:data){
            follow.setListViewType(HomeFollow.TYPE_HISTORY_ITEM);
            history.add(follow);
        }
        follows.addAll(lives);
        if(history.size()>0){
            history.add(0,labelItem);
            follows.addAll(history);
        }
        mAdapter.notifyDataSetChanged();
        listEmpty(follows.size() == 0);
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
        request(HttpConfig.REQUEST_OPERA_REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(follows.size()!=0&&follows.size()<currentAllRecords) {
            request(HttpConfig.REQUEST_OPERA_LOAD);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }


    /**
     * 进入直播间
     */
    public void onEnterRoom(HomeFollow room) {
        KKYUtil.log(TAG, "进入直播间：" + room.getAvRoomId() + "@" + room.getTitle());
        //SDK实例存在
        if(QavsdkControl.getInstance().getAVContext()!=null){
        }else{
            Toast.makeText(getActivity(),getString(R.string.join_room_failed),Toast.LENGTH_LONG).show();
            EnterRoomChecker.getInstance().IMLogin(MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());//重新登录
            return;
        }
        try {
            //如果是自己
            if (room.getHost().getUid().equals(MySelfInfo.getInstance().getId())) {
                Toast.makeText(getActivity(), "this room don't exist", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(getActivity(), RoomVideoRoom.class);
            intent.putExtra(Constants.ID_STATUS, Constants.MEMBER);
            MySelfInfo.getInstance().setIdStatus(Constants.MEMBER);
            CurLiveInfo.setHostID(room.getHost().getUid());
            CurLiveInfo.setHostName(room.getHost().getNickname());
            CurLiveInfo.setHostAvator(room.getHost().getAvatar());
            CurLiveInfo.setRoomNum(Integer.parseInt(room.getAvRoomId()));
            CurLiveInfo.setMembers(Integer.parseInt(room.getWatchCount()) + 1); // 添加自己
            CurLiveInfo.setAdmires(Integer.parseInt(room.getAdmireCount()));
            CurLiveInfo.setAddress(room.getLbs().getAddress());
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 空列表,不加载更多
     */
    public void listEmpty(boolean isEmpty){
        if (ptRefreshView != null) {
            if(isEmpty) {
                ptRefreshView.setMode(PullToRefreshView.Mode.PULL_FROM_START);
            }else{
                ptRefreshView.setMode(PullToRefreshView.Mode.BOTH);
            }
        }
    }

    @Override
    public void onDestroyView() {
        //KKYUtil.cancelRequest(TAG);
        super.onDestroyView();
    }
}
